﻿using FanaticRock.Core.DI;
using FanaticRock.Core.Download;
using FanaticRock.Core.Interfaces;
using FanaticRock.Core.Models;
using FanaticRock.Core.ServiceInterfaces;
using FanaticRock.DownloadManage.Helpers;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;

namespace FanaticRock.DownloadManage
{
    [InjectMe(typeof(IDownloadManageService))]
    public class FanaticDownloadManageService : IDownloadManageService, ILogger
    {
        #region events

        public event EventHandler<FileDownloadCompletedEventArgs> DownloadCompleted;
        public event EventHandler<FileDownloadProgressEventArgs> DownloadProgress;

        #endregion

        #region di

        private ILocalDbService _localDbService;

        #endregion

        #region fields

        ///<summary>下载项列表。</summary>
        private ConcurrentDictionary<string, IntervalDownloadItem> _items = new ConcurrentDictionary<string, IntervalDownloadItem>();
        //private HashSet<DownloadItem> _items =new HashSet<DownloadItem>() ;

        #endregion

        #region ctors

        public FanaticDownloadManageService(ILocalDbService localDbService)
        {
            _localDbService = localDbService;

            DownloadHelper.DownloadProgress += DownloadHelper_DownloadProgress;
            DownloadHelper.DownloadCompleted += DownloadHelper_DownloadCompleted;
        }

        #endregion

        #region download impls

        private async void DownloadHelper_DownloadCompleted(object? sender, Core.Download.FileDownloadCompletedEventArgs e)
        {


            //var downloadItemResult = await _localDbService.Where<DownloadItem>(i => i.LocalPath == e.FilePath);
            //var downloadItem = downloadItemResult.FirstOrDefault();
            //downloadItem.IsCompleted = true;

            //await _localDbService.UpsertAsync(downloadItem);

            DownloadCompleted?.Invoke(sender, e);
        }

        private async void DownloadHelper_DownloadProgress(object? sender, Core.Download.FileDownloadProgressEventArgs e)
        {
            DownloadProgress?.Invoke(sender, e);
        }

        #endregion

        #region methods

        private async Task AddDownloadItemCore(IntervalDownloadItem downloadItem)
        {
            ArgumentNullException.ThrowIfNull(downloadItem);
            //ArgumentException.ThrowIfNullOrWhiteSpace(downloadItem.Uri);
            //ArgumentException.ThrowIfNullOrWhiteSpace(downloadItem.TaskName);
            //ArgumentException.ThrowIfNullOrWhiteSpace(downloadItem.LocalPath);

            //if (_items.TryAdd(downloadItem.Uri, downloadItem))
            //{
            await downloadItem.Download();
            //}
        }

     

        public async Task AddDownloadItem([NotNull] string taskName, [NotNull] string uri, [NotNull] string localPath)
        {
            //var downloadItem = await _localDbService.GetByIdAsync<DownloadItem>(taskName);
            //if (downloadItem == null)
            //{
            //    downloadItem = new DownloadItem(uri, localPath, taskName);
            //}
            //else
            //{
            //    downloadItem.SourceUri = uri;
            //    downloadItem.LocalPath = localPath;
            //}
            //await _localDbService.UpsertAsync(downloadItem);

            //if (HasTaskName(taskName)) throw new ArgumentException($"already exist taskname {taskName}");
            await AddDownloadItemCore(new IntervalDownloadItem(taskName, uri, localPath));
        }

        ///<summary>获得存储。</summary>
        public async Task<IEnumerable<DownloadItem>> GetStorage()
        {
            var result = default(IEnumerable<DownloadItem>);
            await _localDbService.Query<DownloadItem>((source) =>
            {
                result = source.Where(i => i.IsCompleted == true).ToArray();
            });

            return result;
        }


        public async Task Clear()
        {
            await _localDbService.Clear<DownloadItem>();
        }
        #endregion

    }
}
